//
//  WmcRemarkHistoryDBManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/11.
//

import Foundation
import HandyJSON
import YPBedrock

// MARK: - 扩展WmcRemarkHistoryDBManager + WmcDBProtocol

extension WmcRemarkHistoryDBManager: WmcDBProtocol {
    /// 表名
    static var tableName: String = "remark_history"

    /// 表头数据列
    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(), // 主键
            .varchar(name: "remark"), // 实际的备注信息
            .varchar(name: "perview_remark"), // 预览备注信息
            .varchar(name: "perview_history_remark"), // 预览历史备注信息
            .integer(name: "user_id"), // 用户信息
            .varchar(name: "hash"), // 预览哈希唯一信息 用于去重
            .date(name: "save_time"), // 存储时间
        ]
    }

    /// 解析模型
    static func parsingModel(_ dic: [String: Any]) -> WmcRemarkHistoryModel? {
        return WmcRemarkHistoryModel.deserialize(from: dic)
    }
}

// MARK: - [WmcRemarkHistoryDBManager]

struct WmcRemarkHistoryDBManager {
    /// 插入备注
    /// - Parameters:
    ///   - remark: 备注
    ///   - resultBlock: 结果
    static func insertRemark(_ remark: String,
                             resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        // 用户信息
        var userId: Int = 0
        if let _userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !_userId.isEmpty {
            userId = _userId.yp.int
        }
        // 计算唯一哈希
        let hash = "\(remark)\(userId)".yp.hashStr(.md5) ?? "0"
        // 查找是否有一样的数据
        WmcDBManager.shared.searchCustomData(tableName: tableName,
                                             condition: "where hash = \"\(hash)\"") { list in
            if list.count >= 1 { // 有相同数据, 删除所有原数据
                list.forEach { dic in
                    if let id = dic["id"] as? Int { // 遍历移除
                        WmcDBManager.shared.deleteData(tableName: tableName, id: id)
                    }
                }
            }
            // 再进行插入
            let date = WmcDateManager.shared.networkDate.value ?? Date()
            let dateValue = (date.timeIntervalSince1970).yp.int
            // 备注处理
            // 正向循环过找到正确的起始位置
            var startIndex = 0
            if remark.first == "\n" || remark.first == " " {
                for (idx, char) in remark.enumerated() {
                    if char != "\n", char != " " {
                        startIndex = idx
                        break
                    }
                }
            }
            // 倒叙循环找到正确的起始位置
            var endIndex = 0
            if remark.last == "\n" || remark.last == " " {
                for (idx, char) in remark.reversed().enumerated() {
                    if char != "\n", char != " " {
                        endIndex = remark.count - idx - 1
                        break
                    }
                }
            }
            var perviewRemark = remark
            if startIndex != 0, endIndex != 0 {
                perviewRemark = remark.yp.string(at: startIndex ... endIndex) ?? remark
            }
            // 预览备注信息
            let perviewHistoryRemark = remark
                .yp.replacing("\n", with: " ")
            // 调用数据库
            WmcDBManager.shared.insertData(tableName: Self.tableName, insertData: [
                .init(column: Self.dataType[1], value: remark),
                .init(column: Self.dataType[2], value: perviewRemark),
                .init(column: Self.dataType[3], value: perviewHistoryRemark),
                .init(column: Self.dataType[4], value: userId),
                .init(column: Self.dataType[5], value: hash),
                .init(column: Self.dataType[6], value: dateValue),
            ], resultBlock: resultBlock)
        }
    }

    /// 搜索备注历史数据
    /// - Parameters:
    ///   - page: 分页
    ///   - pageSize: 分页大小
    ///   - resultBlock: 结果
    static func searchRemarkHistory(page: Int = 1,
                                    pageSize: Int = 2000,
                                    resultBlock: YPBlock.OneParam<[WmcRemarkHistoryModel]>? = nil)
    {
        // 用户信息
        var userId: Int = 0
        if let _userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !_userId.isEmpty {
            userId = _userId.yp.int
        }
        WmcDBManager.shared.searchData(tableName: tableName,
                                       page: page,
                                       pageSize: pageSize,
                                       isDesc: true) { dicList in
            var modelList: [WmcRemarkHistoryModel] = []
            dicList.forEach { dic in
                if let model = parsingModel(dic) {
                    if model.userId == userId { // 只取当前用户的数据信息
                        modelList.append(model)
                    }
                }
            }
            resultBlock?(modelList)
        }
    }

    /// 删除历史数据
    /// - Parameters:
    ///   - id: id
    ///   - resultBlock: 结果
    static func deleteRemarkHistory(id: Int,
                                    resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        WmcDBManager.shared.deleteData(tableName: tableName, id: id, resultBlock: resultBlock)
    }
}
